const express = require("express");
const router = express.Router();
const fs = require("fs");
const path = require("path");

router.get("/", (req, res) => {
  res.sendFile(path.resolve("index.html"));
});

// 读取模板文件
router.post("/getTemplateContent", (req, res) => {
  let name = req.body.name;
  console.log(name);
  fs.readFile(
    path.resolve(`../client/views/${name}.html`),
    "utf8",
    (err, data) => {
      if (err) {
        res.status(500).json({ error: "Error reading the template file" });
      } else {
        res.status(200).send(data);
      }
    }
  );
});

// 读取views下面的文件
router.get("/getViewsNames", (req, res) => {
  let names = fs.readdirSync(path.resolve("../client/views"));
  names = names.map((name) => name.replace(".html", ""));

  res.json(names);
});
// GET 请求 - 获取所有数据
router.get("/data", (req, res) => {
  res.json(data);
});

// POST 请求 - 创建新数据
router.post("/data", (req, res) => {
  const newData = req.body;
  data.push(newData);
  res.json({ message: "Data added successfully", data: newData });
});

// PUT 请求 - 更新数据
router.put("/data/:id", (req, res) => {
  const id = parseInt(req.params.id);
  const newData = req.body;
  data = data.map((item) => (item.id === id ? { ...item, ...newData } : item));
  res.json({ message: "Data updated successfully" });
});

// DELETE 请求 - 删除数据
router.delete("/data/:id", (req, res) => {
  const id = parseInt(req.params.id);
  data = data.filter((item) => item.id !== id);
  res.json({ message: "Data deleted successfully" });
});

module.exports = router;
